import fs from 'node:fs'
import path from 'node:path'
import { delateFile, isFile, writeFileStr } from './utils'

export function createBootConfig(root: string, config: any, dir: string, name = 'index.json') {
  const bootDir = path.join(root, dir)
  const filePath = path.join(bootDir, name)
  try {
    if (!fs.existsSync(bootDir)) {
      fs.mkdirSync(bootDir)
    }
    if (fs.existsSync(filePath)) {
      delateFile(filePath)
    }
    writeFileStr(filePath, config ? JSON.stringify(config, null, 2) : '{}')
  }
  catch (err) {
    console.error(err)
  }
}
export function createDts(root: string, config: any, dir: string, name = 'mui-env.d.ts') {
  const bootDir = path.join(root, dir)
  const filePath = path.join(bootDir, name)

  try {
    if (dir && !fs.existsSync(bootDir)) {
      fs.mkdirSync(bootDir)
    }
    if (fs.existsSync(filePath)) {
      delateFile(filePath)
    }
    writeFileStr(filePath, config)
  }
  catch (err) {
    console.error(err)
  }
}
export function createNoEnvConfig(root: string, dir: string, jsConfigFilePath = 'index.json') {
  const bootDir = path.join(root, dir)
  const filePath = path.join(bootDir, jsConfigFilePath)
  // 没有文件夹和文件也要创建空的文件，避免页面引入报错
  try {
    if (!fs.existsSync(bootDir)) {
      fs.mkdirSync(bootDir)
      writeFileStr(filePath, '{}')
    }
    else {
      if (!isFile(filePath)) {
        writeFileStr(filePath, '{}')
      }
    }
  }
  catch (err) {
    console.error(err)
  }
}
